import util from '@ohos.util';

export interface TypeSwipe {
  swipe: string
}

export interface TypeOne {
  one: string
}

export interface TypeHome {
  id: number,
  homeImg: string,
  homeName: string,
  homeNameTwo: string,
  homeSwipe: TypeSwipe[],
  homeBright: string,
  homeTitle: string,
  homePrice: string,
  homeValue: string,
  Images: TypeOne[],
  homeConfig: string;
}

class ClsProduct {
  // 定义打开文件地址
  private strFileUrl = "data.json";

  // 异步方式打开JSON文件，并返回数据内容
  async getData(content): Promise<string> {
    return new Promise<string>((resolve, reject) => {
      try {
        let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true });
        content.resourceManager.getRawFileContent(this.strFileUrl).then((rawFile: Uint8Array) => {
          let readString = textDecoder.decodeWithStream(rawFile, { stream: false });
          resolve(readString);
        })
      } catch (e) {
        reject(e.message)
      }
    })
  }

  // 同步方式根据属性名称获取对应数据
  async syncGetDataByAttribute(content, attrName: string) {
    const result = await this.getData(content);
    let arr = JSON.parse(result) as { data: { home: TypeHome [] } };
    return arr.data[attrName]
  }
}

export default new ClsProduct()